package com.nf.health.app.main_intervention.adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.nf.health.app.R;
import com.nf.health.app.customview.MyGridView;
import com.nf.health.app.main_intervention.bean.MedicinedDietBean;
import com.nf.health.app.utils.ImageLoaderUtils;
import com.nf.health.app.utils.TextUtilTools;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by hepann on 2016/11/11.
 * The only genius that is worth anything is the genius for hard work
 *
 * @author hepann
 * @Description
 * @email he_pann@163.com
 */

public class FoodPlanAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private final int TOP = 0;//顶部
    private final int NUTRITION_PERCENT = 1;//营养配比
    private final int COOK_FOOD_MATERIAL = 2;//原料
    private final int COOK_FOOD_OTHER = 3;//制法等..

    private Context ctx;
    private MedicinedDietBean mDietBean;
    //存储要显示的食品组合
    private List<MedicinedDietBean.FoodlistBean.FooddepotBean> mFoodList = new ArrayList<>();

    public FoodPlanAdapter(Context ctx, MedicinedDietBean medicinedDietBean) {
        this.ctx = ctx;
        this.mDietBean = medicinedDietBean;
        this.mFoodList = getFoodList(mDietBean);
    }


    @Override
    public int getItemCount() {
        return 4;
    }

    @Override
    public int getItemViewType(int position) {
        if (position == 0) {
            return TOP;
        } else if (position == 1) {
            return NUTRITION_PERCENT;
        } else if (position == 2) {
            return COOK_FOOD_MATERIAL;
        } else if (position == 3) {
            return COOK_FOOD_OTHER;
        } else {
            return -1;
        }
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == TOP) {//顶部两行
            View viewTop = View.inflate(parent.getContext(), R.layout.activity_food_plan_top, null);
            return new TopViewHolder(viewTop);
        } else if (viewType == NUTRITION_PERCENT) {//营养占比
            View viewNutrition = View.inflate(parent.getContext(), R.layout.activity_food_plan_percent, null);
            return new NutritionViewHolder(viewNutrition);
        } else if (viewType == COOK_FOOD_MATERIAL) {//烹饪步骤
            View viewMaterial = View.inflate(parent.getContext(), R.layout.activity_food_plan_material, null);
            return new CookMaterialHolder(viewMaterial);
        } else if (viewType == COOK_FOOD_OTHER) {
            View viewOther = View.inflate(parent.getContext(), R.layout.activity_food_plan_other, null);
            return new CookOtherHolder(viewOther);
        }
        return null;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof TopViewHolder) {
            TopViewHolder topViewHolder = (TopViewHolder) holder;
            topViewHolder.tvTopMeal.setText("膳食方案 - " + mDietBean.getMeal());
            topViewHolder.tvTime.setText("建议时间: " + mDietBean.getTime() + "  " + mDietBean.getHour() + "  " + mDietBean.getTitle());
        } else if (holder instanceof NutritionViewHolder) {//膳食配比
            NutritionViewHolder nutritionViewHolder = (NutritionViewHolder) holder;
            int foodNum = mDietBean.getFoodlist().size();//食品种类数量

            //食物营养占比,一行最多显示4个
            if (foodNum <= 3) {
                nutritionViewHolder.gvFood.setNumColumns(foodNum);
            } else {
                nutritionViewHolder.gvFood.setNumColumns(4);
            }
            nutritionViewHolder.gvFood.setAdapter(new GvFoodAdapter(ctx, mDietBean));

            //食物图片和用量,根据每个种类需要数量计算总数,每行最多三个
            if (mFoodList.size() < 3) {
                nutritionViewHolder.gvFoodImage.setNumColumns(mFoodList.size());
            } else {
                nutritionViewHolder.gvFoodImage.setNumColumns(3);
            }
            if (mFoodList.size() > 0) {
                nutritionViewHolder.gvFoodImage.setAdapter(new GvFoodImageAdapter(ctx, mFoodList));
            }
        } else if (holder instanceof CookMaterialHolder) {//原料
            CookMaterialHolder CookMaterialHolder = (CookMaterialHolder) holder;
            CookMaterialHolder.tvFoodName.setText("-  " + mDietBean.getName() + "  -");
            ImageLoaderUtils.getinstance(ctx).getImage(CookMaterialHolder.ivFoodImage, mDietBean.getPicture(), R.drawable.default_square_image);
//            CookMaterialHolder.lvYl.setAdapter(new GvYuanLiaoAdapter(ctx, mDietBean));
            addYuanLiaoView(CookMaterialHolder.llYl, mDietBean.getAmount().split("\\|\\|"));
        } else if (holder instanceof CookOtherHolder) {
            CookOtherHolder cookOtherHolder = (CookOtherHolder) holder;
            TextUtilTools.setTextFromHtml(cookOtherHolder.tvZf, getHtmlString(mDietBean.getMethod()));
            TextUtilTools.setTextFromHtml(cookOtherHolder.tvYfDetail, getHtmlString(mDietBean.getUsemethod()));
            TextUtilTools.setTextFromHtml(cookOtherHolder.tvGxDetail, getHtmlString(mDietBean.getEffect()));
        }
    }

    /**
     * 顶部holder
     */
    class TopViewHolder extends RecyclerView.ViewHolder {
        @Bind(R.id.iv_top_icon)
        ImageView ivTopIcon;
        @Bind(R.id.tv_top_meal)
        TextView tvTopMeal;
        @Bind(R.id.tv_time)
        TextView tvTime;

        public TopViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }

    }

    /**
     * 营养占比holder
     */
    class NutritionViewHolder extends RecyclerView.ViewHolder {
        @Bind(R.id.iv_blue)
        ImageView ivBlue;
        @Bind(R.id.iv_refresh)
        ImageView ivRefresh;
        @Bind(R.id.rl_title_parent)
        RelativeLayout rlTitleParent;
        @Bind(R.id.gv_food)
        MyGridView gvFood;
        @Bind(R.id.gv_food_image)
        MyGridView gvFoodImage;

        NutritionViewHolder(View view) {
            super(view);
            ButterKnife.bind(this, view);
            rlTitleParent.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    final RotateAnimation animation = new RotateAnimation(0f, 360f, Animation.RELATIVE_TO_SELF,
                            0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
                    animation.setDuration(500);//设置动画持续时间
                    animation.setAnimationListener(new Animation.AnimationListener() {
                        @Override
                        public void onAnimationStart(Animation animation) {

                        }

                        @Override
                        public void onAnimationEnd(Animation animation) {
                            System.out.println("Jieshu");
                            gvFoodImage.setAdapter(new GvFoodImageAdapter(ctx, getFoodList(mDietBean)));
                        }

                        @Override
                        public void onAnimationRepeat(Animation animation) {

                        }
                    });
                    ivRefresh.startAnimation(animation);
                }
            });
        }
    }


    /**
     * 食物原料holder
     */
    class CookMaterialHolder extends RecyclerView.ViewHolder {
        @Bind(R.id.iv_food_image)
        ImageView ivFoodImage;
        @Bind(R.id.tv_food_name)
        TextView tvFoodName;
        @Bind(R.id.ll_yuanliao)
        LinearLayout llYl;

        CookMaterialHolder(View view) {
            super(view);
            ButterKnife.bind(this, view);
//
        }

    }

    /**
     * 食物原料holder
     */
    class CookOtherHolder extends RecyclerView.ViewHolder {
        @Bind(R.id.tv_yf_detail)
        TextView tvYfDetail;
        @Bind(R.id.tv_zf)
        TextView tvZf;
        @Bind(R.id.rl_yf)
        RelativeLayout rlYf;
        @Bind(R.id.tv_gx_detail)
        TextView tvGxDetail;

        CookOtherHolder(View view) {
            super(view);
            ButterKnife.bind(this, view);
//
        }

    }

    private int[] mFoodShowIndex = new int[]{0, 0, 0, 0, 0, 0, 0};//当前显示的food位置,避免点击刷新而不出现变化

    /**
     * 获取要显示的食物集合
     *
     * @param mDietBean
     * @return
     */
    private List<MedicinedDietBean.FoodlistBean.FooddepotBean> getFoodList(MedicinedDietBean mDietBean) {
        List<MedicinedDietBean.FoodlistBean.FooddepotBean> list = new ArrayList<>();
        for (int i = 0; i < mDietBean.getFoodlist().size(); i++) {
            //获得此类型的食物集合 eg 蔬菜: 萝卜 白菜 青椒 土豆
            List<MedicinedDietBean.FoodlistBean.FooddepotBean> foodList = mDietBean.getFoodlist().get(i).getFooddepot();
            //获得此类型需要的数量
            int num = Integer.valueOf(mDietBean.getFoodlist().get(i).getNum());
            for (int j = 0; j < num; j++) {
                int selextIndx = (mFoodShowIndex[i] + j) % foodList.size();//按顺序向后取(超过了从头继续)
                list.add(foodList.get(selextIndx));
            }
            mFoodShowIndex[i] += num;
        }
        return list;
    }

    /**
     * 显示原料,在ll中添加子view来实现
     * @param llParent
     * @param contents
     */
    private void addYuanLiaoView(LinearLayout llParent, String[] contents) {
        int viewCount = 0;
        if (contents.length % 2 == 0) {
            viewCount = contents.length / 2;
        } else {
            viewCount = contents.length / 2 + 1;
        }
        for (int i = 0; i < viewCount; i++) {
            int left = i * 2;
            int right = i * 2 + 1;
            LinearLayout view = (LinearLayout) View.inflate(ctx, R.layout.item_yuan_liao, null);
            view.setGravity(Gravity.CENTER);
            TextView tvLeft = (TextView) view.findViewById(R.id.tv_left);
            TextView tvRight = (TextView) view.findViewById(R.id.tv_right);
            if (left < contents.length) {
               tvLeft.setText(contents[left]);
            }
            if (right < contents.length) {
                tvRight.setText(contents[right]);
            }
            llParent.addView(view);
        }
    }

    /**
     * 从字符串中分割出食物制法 并设置html样式
     */

    private String getHtmlString(String str) {
        if (TextUtils.isEmpty(str)) {
            return "内容为空";
        }
        if (str.contains("||")) {
            String result[] = str.split("\\|\\|");
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < result.length; i++) {
                if (i != result.length - 1) {
                    sb.append("<font color='#2E86F4'>" + (i + 1) + "." + "</font>" + result[i] + "<br>");
                } else if (i == result.length - 1) {//最后一个字段不加换行
                    sb.append("<font color='#2E86F4'>" + (i + 1) + "." + "</font>" + result[i]);
                }
            }
            return sb.toString();
        } else {
            return str;
        }
    }
}
